import { router } from '@/router/index'
import { useAuth } from '@/stores/auth'
import { useSettings } from '@/stores/settings'
import { menuRoutes } from '@/router/routes'
import lodash from 'lodash'
import { message } from 'ant-design-vue'

let routes: { name: string }[] = [] //该路由数组用于给cms菜单赋值

/**
 * 将接口返回的路由列表转换为router.ts中定义的路由列表
 * @param data
 */
export function handlePermissionRoutes(data: string[]) {
  // TODO 路由keys
  const routeKeys = [...data, '']
  // const routeKeys = ['plant', 'plantJinfo', 'plantSchool', 'plantTibetan', 'exam', 'examList', 'student', 'examPaper', 'statistics', 'message', 'system', 'systemAccount', 'systemRole', '']
  const filterRoutes = lodash.cloneDeep(menuRoutes)
  return filterFn(filterRoutes, routeKeys)
}

// 过滤路由 start
function onFilterFirstLevel(routes: any, routeKeys: string[]): any[] {
  if (Array.isArray(routes)) {
    return routes.filter((route) => {
      return routeKeys.includes(route.name)
    })
  } else {
    return []
  }
}

function onFilterSecondLevel(routes: any[], routeKeys: string[]) {
  return routes.map((route) => {
    if (route.children?.length) {
      route.children = onFilterFirstLevel(route.children, routeKeys)
    }
  })
}

function filterFn(routes: any[], routeKeys: string[]) {
  const first = onFilterFirstLevel(routes, routeKeys)
  if (first.length) {
    onFilterSecondLevel(first, routeKeys)
  }
  return first
}

// 过滤路由 end

/**
 * 生成对应用户的权限路由
 */
export const dynamicRoutes = async () => {
  const store = useAuth()
  const token = store?.token
  if (token) {
    await useAuth().getUserInfo()
    const result = getRouteTreeName(useAuth().userInfo.menu_list)
    const filterRoutes = handlePermissionRoutes(result)
    if (Array.isArray(filterRoutes) && filterRoutes.length) {
      filterRoutes.forEach((item) => {
        router.addRoute(item) //退出登录时，需要将router的路由还原至初始数据
      })
      routes = lodash.cloneDeep(filterRoutes)
      filterCacheRoutes(routes)
      return true
    } else {
      await message.error('暂无访问权限！', 1)
      await router.push('')
      return
    }
  }
}

/**
 * 获取会被keepAlive组件缓存的路由组件
 */
export function filterCacheRoutes(routes: any[]) {
  const cacheRoutes = routes.filter((route) => {
    return route.meta.keepAlive
  })
  const cacheRouteNames = cacheRoutes.map((cache) => {
    return cache.name
  })
  const settingStore = useSettings()
  settingStore.$patch({
    cacheRoutes: cacheRouteNames
  })
}

/**
 * 获取接口返回路由数组的name
 */
function getRouteTreeName(Routes: any) {
  if (!Array.isArray(Routes)) {
    return []
  }
  const fun = (pre: any, cur: any) => {
    if (cur.children) {
      pre = cur.children.reduce(fun, pre)
      return pre.concat([cur.name])
    }
    return pre
  }
  return Routes.reduce(fun, [])
}

export { routes }
